package com.example.nutritionmate.service;

import com.example.nutritionmate.dto.NutrientAmountDTO;
import com.example.nutritionmate.dto.NutritionFactDTO;
import com.example.nutritionmate.entity.NutritionFact;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.repository.MealNutritionRepository;
import com.example.nutritionmate.repository.NutritionFactRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NutritionService {

    @Autowired
    private NutritionFactRepository nutritionFactRepository;

    @Autowired
    private MealNutritionRepository mealNutritionRepository;

    /**
     * 获取所有营养成分
     *
     * @return List<NutritionFactDTO>
     */
    public List<NutritionFactDTO> getAllNutritionFacts() {
        List<NutritionFact> nutritionFacts = nutritionFactRepository.findAll();
        return nutritionFacts.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public List<NutrientAmountDTO> getNutritionAmountByDate(User user, LocalDate date) {
        // 查询营养成分汇总
        List<MealNutritionRepository.NutritionSummary> summaries = mealNutritionRepository.findNutritionSummaryByUserAndDate(user, date);

        // 转换为 DTO
        List<NutrientAmountDTO> nutrientAmounts = summaries.stream()
                .map(summary -> {
                    NutrientAmountDTO dto = new NutrientAmountDTO();
                    dto.setNutritionId(summary.getNutritionId());
                    dto.setNutritionName(summary.getNutritionName());
                    dto.setAmount(summary.getTotalAmount());
                    dto.setUnit(summary.getUnit());
                    return dto;
                })
                .collect(Collectors.toList());

        return nutrientAmounts;
    }


    /**
     * 将 NutritionFact 实体转换为 NutritionFactDTO
     *
     * @param nutritionFact NutritionFact 实体
     * @return NutritionFactDTO
     */
    private NutritionFactDTO convertToDTO(NutritionFact nutritionFact) {
        NutritionFactDTO dto = new NutritionFactDTO();
        dto.setNutritionId(nutritionFact.getNutritionId());
        dto.setNutritionName(nutritionFact.getNutritionName());
        dto.setNutritionNameEn(nutritionFact.getNutritionNameEn());
        dto.setUnit(nutritionFact.getUnit());
        return dto;
    }
}
